﻿using SuporeSliplampApp.DataAccess;
using SuporeSliplampApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using FellowOakDicom;
using FellowOakDicom.Network;
using FellowOakDicom.Network.Client;
using System.Windows;

namespace SuporeSliplampApp.Service
{
    public class DicomPatientService
    {
        public async Task<List<PatientModel>> GetPatientsFromDicomClient(IDicomClient dicomClient)
        {
            var patientList = new List<PatientModel>();

            var request = new DicomCFindRequest(DicomQueryRetrieveLevel.Patient);
            request.Dataset.Add(DicomTag.PatientName, "*");
            request.OnResponseReceived += (req, response) =>
            {
                if (response.HasDataset)
                {
                    var patient = new PatientModel
                    {
                        Name = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty),
                        P_ID = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty),
                        SEX = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientSex, string.Empty),
                        Birth = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientBirthDate, DateTime.MinValue),
                        Adreess = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientAddress, string.Empty),
                        PhoneNum = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientTelephoneNumbers, string.Empty),
                        Email = response.Dataset.GetSingleValueOrDefault(DicomTag.PatientComments, string.Empty),
                        InsertDate = DateTime.Now
                    };
                    patientList.Add(patient);
                }
            };

            await dicomClient.AddRequestAsync(request);
            try
            {
                await dicomClient.SendAsync();
            }
            catch (DicomAssociationAbortedException ex)
            {
                Console.WriteLine("DICOM association aborted: " + ex.Message);
                Console.WriteLine("Source: " + ex.Source);
                Console.WriteLine("Stack Trace: " + ex.StackTrace);
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.Message);
                Console.WriteLine("Source: " + ex.Source);
                Console.WriteLine("Stack Trace: " + ex.StackTrace);
            }

            return patientList;
        }
    }
}
